//引入一个gulp包
var gulp = require("gulp");

//引入sass模块
var sass = require("gulp-sass");
//压缩css文件
var cssnano = require("gulp-cssnano");
//合并
var concat = require('gulp-concat');

//task任务
gulp.task("scss", function() {
    gulp.src(["src/scss/**/*.scss", "!src/scss/**/_*.scss"])  //找到源文件路径
	    .pipe(sass())  //编译sass文件
	    .pipe(gulp.dest("src/css"))  //将sass转换成css文件
	    .pipe(cssnano())  //压缩css文件
	    .pipe(gulp.dest("dist/css"))  //放入dist文件夹下的css文件夹下
});

//编译公共的js文件和css文件
gulp.task('common',function(){
    gulp.src('src/common/js/*.*')   //commonJS
    	.pipe(gulp.dest('dist/common/js'));
    gulp.src('src/common/css/*.*')   //commonCSS
    	.pipe(gulp.dest('dist/common/css'));
    gulp.src('src/common/fonts/*.*')
    	.pipe(gulp.dest('dist/common/fonts'));
});

//引入uglify模块，编译js文件
var uglify = require("gulp-uglify");
gulp.task("js", function(){
    gulp.src(["src/js/**/*.js"])   //文件路径
        .pipe(uglify())   //压缩js文件
        .pipe(gulp.dest("dist/js"));   
});

//gulp.task("common",function(){
//	gulp.src(["src/common/**/*.js"])
//      .pipe(gulp.dest("dist/common"));
//});
//
//
//gulp.task("common",function(){
//	gulp.src(["src/common/**/*.css"])
//      .pipe(gulp.dest("dist/common"));
//});


//图片压缩
var imagemin = require("gulp-imagemin");  //优化图片
var cache = require("gulp-cache");  //减少图片重复压缩
gulp.task("images", function() {
    gulp.src("src/img/**/*.{png,jpg,gif}")
        .pipe(cache(imagemin({
            progressive:true,
            svgoPlugins:[{removeViewBox:false}],
            interlaced: true
        })))
        .pipe(gulp.dest("dist/img"));
});

//html文件压缩，发布静态页面到dist文件夹
var htmlmin = require("gulp-htmlmin");
gulp.task("html", function() {
    gulp.src("src/**/*.html")
        .pipe(htmlmin({
            collapseWhitespace: true,
            removeComments: true
        }))
        .pipe(gulp.dest("dist/"));
});
 
//监听默认事件
gulp.task("watch", ["common", "scss", "js", "images", "html"],function() {    
    gulp.watch("src/scss/**/*.scss", ["scss"]);
    gulp.watch("src/js/**/*.js",["js"]);
    gulp.watch('src/img/**/*.*',["images"]);
    gulp.watch('src/**/*.html',["html"]);
});

gulp.task("default", function() {  
    gulp.start(["scss", "js", "common","images", "html", "watch"]);  
});